/* eslint-disable no-debugger */
import { useLocation, Navigate } from "react-router-dom";
import { searchRoute } from "@/utils/routerUtils";
import { rootRouter } from "@/routers";
import { RootState, useSelector, useDispatch } from "@/store";
import { getTitle } from "@/utils/envUtils";
import { AxiosCanceler } from "@/utils/http/axios/axiosCancel";
import useRouter from "@/hooks/useRouter";
import { PageEnum } from "@/enums/PageEnum";
import { setCurrentRoute } from "@/store/modules/global";
import { useEffect, useState } from "react";
const axiosCanceler = new AxiosCanceler();
/**
 * @description 路由守卫组件
 * */
const AuthRouter = (props: { children: JSX.Element }) => {
	const { setRouter } = useRouter();
	const { token } = useSelector((state: RootState) => state.global);
	// * Dynamic Router(动态路由，根据后端返回的菜单数据生成的一维数组)
	const { authRouter } = useSelector((state: RootState) => state.auth);
	const { pathname } = useLocation();
	// const dispatch = useDispatch();
	const route = searchRoute(pathname, rootRouter);
	// 在跳转路由之前，清除所有的请求
	axiosCanceler.removeAllPending();
	// * 在跳转路由之前，清除所有的请求
	setRouter(route);
	// dispatch(setCurrentRoute(route));
	//设置标题
	setTitle(route);
	// * 判断当前路由是否需要访问权限(不需要权限直接放行)
	if (!route.meta?.requiresAuth) return props.children;
	// * 判断是否有Token
	if (!token) return <Navigate to={PageEnum.BASE_LOGIN} replace />;
	// * Static Router(静态路由，必须配置首页地址，否则不能进首页获取菜单、按钮权限等数据)，
	// * 获取数据的时候会loading，所有配置首页地址也没问题
	const staticRouter = [PageEnum.BASE_HOME, PageEnum.BASE_NO_AUTH];
	const routerList = authRouter.concat(staticRouter);
	// * 如果访问的地址没有在路由表中重定向到403页面
	if (routerList.indexOf(pathname) == -1) return <Navigate to={PageEnum.BASE_NO_AUTH} />;
	// * 当前账号有权限返回 Router，正常访问页面
	return props.children;
};

// const AuthRouter = (props: { children: JSX.Element }) => {
// 	const { setRouter } = useRouter();
// 	const { token } = useSelector((state: RootState) => state.global);
// 	const { authRouter } = useSelector((state: RootState) => state.auth);
// 	const { pathname } = useLocation();
// 	const route = searchRoute(pathname, rootRouter);
// 	useEffect(() => {
// 		// 在跳转路由之前，清除所有的请求
// 		axiosCanceler.removeAllPending();
// 		// dispatch(setCurrentRoute(route));
// 		setTitle(route);
// 		setRouter(route);
// 	}, [pathname]);

// 	if (!token) {
// 		return <Navigate to={PageEnum.BASE_LOGIN} replace />;
// 	}
// 	const routeRequiresAuth = route.meta?.requiresAuth;

// 	if (!routeRequiresAuth) {
// 		return props.children;
// 	}
// 	// @ts-ignore
// 	const isStaticRoute = [PageEnum.BASE_HOME, PageEnum.BASE_NO_AUTH].includes(pathname);
// 	const isAuthRoute = authRouter.some((r: string) => r === pathname);

// 	if (!isStaticRoute && !isAuthRoute) {
// 		return <Navigate to={PageEnum.BASE_NO_AUTH} />;
// 	}

// 	return props.children;
// };

const setTitle = (route: any) => {
	window.document.title = `${getTitle()} ${route?.meta?.title ? " | " + route?.meta?.title : ""}`;
};

export default AuthRouter;
